<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span
          class="arrow"
          @click="$router.back()"
        ><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? '编辑' : '添加' }}角色</span>
      </div>
      <div class="right">蓝景程序员</div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="active">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="active === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="addForm"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="active === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="item in treeList" :key="item.id" class="tree-item">
            <div class="tree-title">{{ item.title }}</div>
            <!-- check-strictly 让父子节点之间没有关系 -->
            <el-tree
              ref="tree"
              :data="item.children"
              show-checkbox
              default-expand-all
              node-key="id"
              highlight-current
              check-strictly
              :props="{ label: 'title' }"
            />
          </div>
        </div>
      </div>
      <div v-show="active === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="disabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="defaultProps"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <!-- 如果是第一步 上一步按钮需要隐藏 -->
        <el-button v-show="active !== 1" @click="prev">上一步</el-button>
        <!-- 只要不是第三步 就是显示 下一步 -->
        <el-button
          v-if="active !== 3"
          type="primary"
          @click="next"
        >下一步</el-button>
        <el-button v-else type="primary" @click="onSubmit">确定添加</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addRoleAPI, getSysRoleTreeAPI, getSysRoleDetailAPI, updateRoleUserAPI } from '@/api/role'
export default {
  name: 'RoleAdd',
  data() {
    return {
      defaultProps: { label: 'title', disabled: () => true },
      active: 1,
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      treeList: [] // 所有的权限
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getSysRoleTree()
    // 如果是编辑 才发送请求获取角色的详情数据
    if (this.id) {
      this.getSysRoleDetail(this.id)
    }
  },
  methods: {
    // 获取角色的详情数据
    async getSysRoleDetail(id) {
      try {
        const res = await getSysRoleDetailAPI(id)
        // console.log(res)
        this.roleForm = res.data
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    async onSubmit() {
      try {
        if (this.id) {
          delete this.roleForm.userTotal
          // 编辑
          await updateRoleUserAPI(this.roleForm)
          this.$message.success('编辑角色成功')
        } else {
          // 添加
          await addRoleAPI(this.roleForm)
          this.$message.success('添加角色成功')
        }

        this.$router.push('/sys/role')
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 获取所有的权限
    async getSysRoleTree() {
      try {
        const res = await getSysRoleTreeAPI()
        // console.log(res)
        this.treeList = res.data
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    async next() {
      if (this.active === 3) return
      // 判断 是否是 第一步
      if (this.active === 1) {
        // 兜底校验
        await this.$refs.addForm.validate()
        this.active++
        if (this.id) {
          // 回显第二步
          this.$refs.tree.forEach((item, index) => {
            item.setCheckedKeys(this.roleForm.perms[index])
          })
        }
      } else if (this.active === 2) {
        // 添加
        this.roleForm.perms = []
        this.$refs.tree.forEach((item) => {
          // 将选中的权限点 添加 roleForm 的 perms 属性
          this.roleForm.perms.push(item.getCheckedKeys())
        })

        // 判断数组的长度 perms 二组数组
        if (this.roleForm.perms.flat().length === 0) {
          return this.$message.error('请至少选择一个权限')
        }
        this.active++
        // 将第三步的权限列表进行回显
        this.$refs.disabledTree.forEach((item, index) => {
          item.setCheckedKeys(this.roleForm.perms[index])
          // console.log(item)
        })
      }
    },
    prev() {
      if (this.active === 1) return
      this.active--
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info {
          font-size: 14px;
          color: #666;
          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;
      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
